<template>
  <div class="mc-container">
    <div>
      <el-button :icon="Edit" plain type="primary" @click="toUpdate">
        修改
      </el-button>
      <el-button :icon="Search" plain type="primary" @click="openInvQuery">
        选择存货
      </el-button>
      <el-button
        :disabled="!state.isEdit"
        :icon="SuccessFilled"
        plain
        type="primary"
        @click="toSave"
      >
        保存
      </el-button>
      <el-button
        :disabled="!state.isEdit"
        plain
        type="primary"
        @click="addBatchRuleB()"
      >
        <vab-icon icon="sort-desc" />
        增行
      </el-button>
      <el-button
        :disabled="!state.isEdit"
        :icon="Delete"
        plain
        type="warning"
        @click="deleteRow"
      >
        删行
      </el-button>
    </div>
    <div style="height: 20px"></div>
    <el-row>
      <el-col :span="4">
        <div class="custom-tree-node-container">
          <span style="font-size: 17px; font-weight: bold">存货分类</span>
          <el-tree
            :data="state.treeData"
            :expand-on-click-node="false"
            :highlight-current="true"
            node-key="pkInvcl"
            :props="{ children: 'downs', label: 'invclName' }"
            @node-click="handleNodeClick"
          />
        </div>
        <div style="padding-top: 10px">
          <p style="font-size: 17px; font-weight: bold">存货编码</p>
          <p
            v-for="i in state.invBatchRuleList"
            :key="i.pkBatchRuleH"
            style="margin-left: 15px; cursor: pointer"
            @click="invbrClick(i.batchRuleCode)"
          >
            {{ i.batchRuleCode }}
          </p>
        </div>
      </el-col>
      <el-col :span="1" />
      <el-col :span="18">
        <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
          <el-row :gutter="12">
            <el-col :span="6">
              <el-form-item label="规则对象">
                <el-input v-model="form.refTypeObject" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规则类型">
                <el-input v-model="form.refTypeName" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规则名称" prop="batchRuleName">
                <el-input
                  v-model="form.batchRuleName"
                  :disabled="!state.isEdit"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="编码规则" prop="formatName">
                <el-input v-model="form.formatName" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="12">
            <el-table
              :data="state.batchRuleBList"
              highlight-current-row
              style="width: 100%"
            >
              <el-table-column label="级次" type="index" width="100" />
              <el-table-column label="数据源类型" prop="sourceName" width="300">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.pkRuleSource"
                    class="m-2"
                    filterable
                    placeholder="选择"
                    @change="ruleSourceChange($event, scope.$index)"
                  >
                    <el-option
                      v-for="rs in state.ruleSourceList"
                      :key="rs.pkRuleSource"
                      :label="rs.sourceName"
                      :value="rs.pkRuleSource"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="格式" prop="sourceFormat" width="300">
                <template #default="scope">
                  <el-input
                    v-if="scope.row.sourceType == 1"
                    v-model="scope.row.sourceFormat"
                    disabled
                  />
                  <el-input
                    v-if="scope.row.sourceType == 2"
                    v-model="scope.row.sourceFormat"
                  />
                  <el-input
                    v-if="scope.row.sourceType == 3"
                    v-model="scope.row.sourceFormat"
                  />
                </template>
              </el-table-column>
              <el-table-column label="长度" prop="formatLength" />
            </el-table>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <QueryInv ref="inv" @selected-callback="inventoryCallback" />
  </div>
</template>

<script setup>
  import { getAllInvclApi } from '@/api/base/invcl'
  import { getRuleSourceListApi } from '@/api/kc/rule_source'
  import {
    addBatchRuleApi,
    updateBatchRuleApi,
    getBatchRuleInfoApi,
    getBatchRuleListApi,
  } from '@/api/kc/batch_rule'
  import QueryInv from '@/plugins/InventorySelector/invSelect.vue'
  import { Search, Delete, Edit, SuccessFilled } from '@element-plus/icons-vue'
  import { localStorageConfig } from '@/config/localstorage.config'
  const $baseMessage = inject('$baseMessage')
  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
  const inv = ref()
  const formRef = ref(null)
  const rules = reactive({
    batchRuleName: [
      { required: true, trigger: 'blur', message: '请输入规则名称' },
    ],
  })

  const state = reactive({
    isEdit: false,
    treeData: [],
    treeNode: {},
    batchRuleBList: [],
    ruleSourceList: [],
    curRow: {},
    invBatchRuleList: [],
  })

  const form = reactive({ refTypeName: '', refTypeObject: '', pkCorp: pkCorp })

  const openInvQuery = () => {
    inv.value.handleOpen({ isComsume: 1 }, 0)
  }

  const inventoryCallback = (inventoryInfo) => {
    form.batchRuleCode = inventoryInfo.invcode
    form.batchRuleName = ''
    form.refTypeObject = inventoryInfo.invcode
    form.refType = 0
    form.refTypeName = '存货编码'
    form.pkBatchRuleH = ''
    state.batchRuleBList = []
    state.isEdit = false
    getBatchRuleInfo()
  }

  const getRuleSourceList = async () => {
    const { code, data } = await getRuleSourceListApi({})
    if (code === 2000) {
      state.ruleSourceList = data
    }
  }
  const getInvClTreeData = async () => {
    const { code, data } = await getAllInvclApi({ pkCorp: pkCorp })
    if (code === 2000) {
      state.treeData = data
    }
  }
  const getBatchRuleList = async () => {
    const { code, data } = await getBatchRuleListApi({
      pkCorp: pkCorp,
      refType: 0,
    })
    if (code === 2000) {
      state.invBatchRuleList = data
    }
  }

  const invbrClick = (val) => {
    state.isEdit = false
    form.batchRuleCode = val
    form.refTypeObject = val
    form.refType = 0
    form.refTypeName = '存货编码'
    getBatchRuleInfo()
  }

  const handleNodeClick = async (treeData) => {
    state.treeNode = treeData
    if (state.treeNode.downs.length <= 0) {
      form.batchRuleCode = treeData.invclCode
      form.batchRuleName = ''
      form.refTypeObject = treeData.invclCode
      form.refType = 1
      form.refTypeName = '存货分类'
      form.pkBatchRuleH = ''
      state.batchRuleBList = []
      state.isEdit = false
      getBatchRuleInfo()
    }
  }

  const ruleSourceChange = (val, index) => {
    const obj = state.ruleSourceList.find((item) => {
      return item.pkRuleSource === val
    })
    state.batchRuleBList[index].sourceType = obj.sourceType
  }

  const toUpdate = () => {
    if (form.batchRuleCode) {
      state.isEdit = true
    } else {
      $baseMessage('请选择相关存货分类或存货编码！', 'warning')
    }
  }
  const addBatchRuleB = () => {
    state.batchRuleBList.push({})
  }
  const deleteRow = () => {
    const index = state.batchRuleBList.indexOf(state.curRow)
    state.batchRuleBList.splice(index, 1)
  }
  const getBatchRuleInfo = async () => {
    let params = {
      batchRuleCode: form.batchRuleCode,
      pkCorp: pkCorp,
    }
    const { code, data } = await getBatchRuleInfoApi(params)
    if (code === 2000 && null !== data) {
      form.pkBatchRuleH = data.pkBatchRuleH
      form.batchRuleName = data.batchRuleName
      state.batchRuleBList = data.batchRuleBList
    } else {
      form.pkBatchRuleH = ''
      form.batchRuleName = ''
      state.batchRuleBList = []
    }
  }

  const toSave = async () => {
    form.batchRuleBList = state.batchRuleBList
    formRef.value.validate(async (valid) => {
      if (valid) {
        let res = null
        if (form.pkBatchRuleH) {
          res = await updateBatchRuleApi(form)
        } else {
          res = await addBatchRuleApi(form)
        }
        if (res && res.code === 2000) {
          getBatchRuleList()
          $baseMessage(res.msg, 'success')
        }
      }
    })
  }

  const showDefault = () => {
    getInvClTreeData()
    getRuleSourceList()
    getBatchRuleList()
  }
  onMounted(async () => await showDefault())
</script>

<style scope>
  .is-penultimate > .el-tree-node__content {
    color: #626aef;
  }

  .el-tree-node.is-expanded.is-penultimate > .el-tree-node__children {
    display: flex;
    flex-direction: row;
  }
  .is-penultimate > .el-tree-node__children > div {
    width: 25%;
  }
</style>
